package ch.sfug.anim.tween {	import ch.sfug.anim.IAnimation;	
	
	import flash.events.EventDispatcher;	import flash.utils.getTimer;		import ch.sfug.events.TweenEvent;	import ch.sfug.util.EnterFrame;	
	/**	 * @author mich	 */	public class AbstractTween extends EventDispatcher implements IAnimation {
		protected var t:Object;		protected var d:uint;
		private var s:uint;
		public function AbstractTween( t:Object, d:int = 1000 ) {			super();			target = t;			duration = d;		}
		
		public function start():void {			if( t != null ) {				s = getTimer();				EnterFrame.add( update );				update();				dispatchEvent(new TweenEvent(TweenEvent.TWEEN_START));			} else {				throw new Error( "cant start tween with a null target" );			}		}
		
		public function stop():void {			EnterFrame.remove( update );			dispatchEvent(new TweenEvent(TweenEvent.TWEEN_END));		}
		
		private function update(  ):void {			var c:uint = getTimer() - s;			if( c < d ) {				interpolate(c, d);			} else {				interpolate(1, 1);				stop();			}		}		
		/**
		 * abstract function		 * @param c the current time		 * @param d the total time		 */		protected function interpolate( c:Number, d:Number):void {			if( hasEventListener(TweenEvent.TWEEN_UPDATE) ) dispatchEvent(new TweenEvent(TweenEvent.TWEEN_UPDATE));		}
		
		/**		 * the default easing function		 */		public static function linear( t:Number, b:Number, c:Number, d:Number ):Number {			return b + t * c / d;		}
		
		/**		 * sets/gets the duration of the tween		 */		public function set duration( d:uint ):void {			if( d > 0 ) {				this.d = d;			} else {				throw new Error(" you have to specify a duration bigger than 0 and not: " + d + " for the tween: " + this);			}		}
		
		public function get duration(  ):uint {			return d;		}
		
		/**		 * sets/gets the target of the tween		 */		public function set target( t:Object ):void {			this.t = t;		}
		
		public function get target(  ):Object {			return t;		}
		
		public override function toString():String {			return "AbstractTween( " + t + ", " + d + " )";		}	}}